class MyPage extends BaseList {
    constructor(action, orderby, flag, $pagesize, $pagination, cokiePageSize, cokiePageIndex, cokieListResult, listUrl, delUrl) {
        super(action, orderby, flag, $pagesize, $pagination, cokiePageSize, cokiePageIndex, cokieListResult, listUrl, delUrl);
        this.selectedItemList = {};  // 选定的数据列表OnMultiChoice
        this.draggedItemList = [];
        this.filterCatalogueFlag = 1;
        this.dragging = 0;
    }
    OnPageLoad() {
        let _pageindex = $.cookie(this.cokiePageIndex) === undefined ? 1 : $.cookie(this.cokiePageIndex);
        if (this.flag === 0) {
            _pageindex = 1;
        } else {
            this.RestoreFilters();  // 恢复过滤条件
        }
        this.$pagination.attr("_msh_page", _pageindex);

        _InstanceTree.InitTreeObject();
    }
    SetCriterion(item) {
        // 设置目录条件
        if (parseInt(this.filterCatalogueFlag) === 1) {
            item['CatalogueId'] = parseInt($.trim($('#NodeId').val()) === '' ? 0 : $.trim($('#NodeId').val()));
        }

        // 设置材料检索条件       
        item['Begin'] = $.trim($('#Begin').val()) === '' ? null : $.trim($('#Begin').val());
        item['End'] = $.trim($('#End').val()) === '' ? null : $.trim($('#End').val());
        item['StyleNo'] = $.trim($('#StyleNoFilterValue').val()) === '' ? null : $.trim($('#StyleNoFilterValue').val());
        item['CustomerName'] = $.trim($('#CustomerNameFilterValue').val()) === '' ? null : $.trim($('#CustomerNameFilterValue').val());
        item['DesignedByName'] = $.trim($('#DesignedByNameFilterValue').val()) === '' ? null : $.trim($('#DesignedByNameFilterValue').val());
        item['GradedByName'] = $.trim($('#GradedByNameFilterValue').val()) === '' ? null : $.trim($('#GradedByNameFilterValue').val());
        item['Description'] = $.trim($('#DescriptionFilterValue').val()) === '' ? null : $.trim($('#DescriptionFilterValue').val());
        item['TypeFlag'] = '1';
        return item;
    }
    GetFilter(pageIndex) {
        let item = super.GetFilter(pageIndex);
        // 设置条件
        item = this.SetCriterion(item);

        return JSON.stringify(item);
    }
    FetchByFilter() {
        this.filterCatalogueFlag = 0;
        this.FetchForPage(1);
    }
    FetchAll() {
        $("#Begin").val("");
        $("#End").val("");
        $("#StyleNoFilterValue").val("");
        $("#CustomerNameFilterValue").val("");
        $("#DesignedByNameFilterValue").val("");
        $("#GradedByNameFilterValue").val("");
        $("#DescriptionFilterValue").val("");

        this.filterCatalogueFlag = 1;
        this.$pagination.attr("_msh_page", 1);
        this.FetchForPage(1);
    }
    EmptyTableContent() {
        $("#tabData01 tbody").empty();
        $("#tabData02 tbody").empty();
        this.$pagination.attr("_msh_page", 1);
    }
    SetTableContent(result) {
        $("#tabData01 tbody").empty();
        $("#tabData02 tbody").empty();

        let content_01 = '';
        let content_02 = '';
        this.numCheckbox = result.length;  // 设置表格中checkbox的数量为表格的行数
        for (let i = 0; i < result.length; i++) {
            content_01 += '<tr _mash_id="' + result[i].headerId + '">';
            content_01 += '<td style="padding-left:5px; vertical-align:middle;"><label class="btn" for="R-' + result[i].headerId + '"><input id="R-' + result[i].headerId + '" name="_check_row" type="checkbox" onclick="_Instance.DoCheckRow($(this),\'_check_row\', $(\'#CheckAll\'));" value="' + result[i].headerId + '"/><i></i><span></span></label></td>';
            content_01 += '<td class="column__action"><span title="编辑" class="edit" onclick="_Instance.DoEdit($(this));"><i class="fa-all fa-pencil fa-1"></i></span></td>';
            if (result[i].quotedFlag === 1) {
                content_01 += '<td></td>';
            } else {
                // 删除权限判断
                if ($("#ActionAcl_4").length === 0 || parseInt($("#ActionAcl_4").val() === 0)) {
                    content_01 += '<td></td>';
                } else {
                    if ((parseInt($("#UserId").val()) === parseInt(result[i].designedBy)) || ($("#RoleName").val().indexOf("系统管理员") !== -1)) {
                        content_01 += '<td class="column__action"><span title="删除" class="trash" onclick="_Instance.DoDelete($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
                    } else {
                        content_01 += '<td></td>';
                    }
                }
            }
            content_01 += '<td>' + formatNullData(result[i].styleNo) + '</td>';
            content_01 += '<td>' + result[i].productName + '</td>';
            content_01 += '<td>' + formatNullData(result[i].customerName) + '</td>';
            content_01 += '</tr>';

            content_02 += '<tr>';
            content_02 += '<td>' + formatNullData(result[i].dateOfFilling) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].designedByName) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].gradedByName) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].description) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].ic_ColourSampleIndication) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].embroideryLaceAndOther) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].notes) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].updatedByName) + '</td>';
            content_02 += '<td style="border-right:none;">' + formatNullData(result[i].updatedDate) + '</td>';
            content_02 += '</tr>';

            $("#tabData01 tbody").append(content_01);
            $("#tabData02 tbody").append(content_02);
            content_01 = '';
            content_02 = '';
        }
        setTwoTableRowColor("tabData01", "tabData02");

        let _this = this;
        // 为拖动做准备
        $("#tabData01 tbody tr").mousedown(function (event) {
            if (_this.draggable === 1)
                return false;
            // 如果鼠标按下的位置 正好是选择框，则不做拖动处理
            if ($(event.target).closest("td").index() === 0)
                return false;
            if (parseInt($(this).attr("_msh_flag")) === 1)
                return false;  // 如果是系统用户，则不做任何操作
            if ($(this).hasClass("row__selected") === true) {
                _this.draggable = 1;
                event.preventDefault();
                _InstanceTree.CreateDragLayer(event);
                _this.GetDragData();
                $(window).mousemove(function (event) {
                    event.preventDefault();
                    _InstanceTree.FollowMe(event);
                }).mouseup(function (event) {
                    _this.draggable = 0;
                    _this.draggedItemList = [];
                    $(window).unbind('mousemove');
                    $(window).unbind('mouseup');

                    if ($("#moveLayerId").length) {
                        $("#moveLayerId").remove();
                    }
                });
            }
        });
        $("#tabData02 tbody tr").mousedown(function (event) {
            if (_this.dragging === 1)
                return false;
            if (parseInt($(this).attr("_msh_flag")) === 1)
                return false;  // 如果是系统用户，则不做任何操作
            if ($(this).hasClass("row__selected") === true) {
                _this.dragging = 1;
                event.preventDefault();
                _this.CreateDragLayer(event);
                _InstanceTree.GetDragData();
                $(window).mousemove(function (event) {
                    event.preventDefault();
                    _InstanceTree.FollowMe(event);
                }).mouseup(function (event) {
                    _this.dragging = 0;
                    _this.draggedItemList = [];
                    $(window).unbind('mousemove');
                    $(window).unbind('mouseup');

                    if ($("#moveLayerId").length) {
                        $("#moveLayerId").remove();
                    }
                });
            }
        });

        this.ResetSelectRowStatus();  // 恢复选定结果
    }
    DoEditCatalogue() {
        // 设置当前页
        $.cookie(this.cokiePageIndex, parseInt(this.$pagination.attr("_msh_page")));
        // 保存过滤条件
        this.SaveFilters();
        location.assign(parent.basePath + '/tech/piece_yardage/catalogue/edit.html');
    }
    DoInsert() {
        super.DoInsert();
        // 保存树状态
        let ref = $.jstree.reference('treeContent');
        ref.save_state();
        location.assign(parent.basePath + '/tech/piece_yardage_onesize/auxiliary/1/0/' + $("#NodeId").val() + '/edit.html');
    }
    DoEdit($self) {
        super.DoEdit();
        // 设置当前检索后的数据列表标识数组
        let _arrayResultList = new Array();
        $("#tabData01 tbody tr").each(function (index) {
            _arrayResultList.push($(this).attr("_mash_id"));
        });
        $.cookie(this.cokieListResult, _arrayResultList.join(","));

        // 保存树状态
        let ref = $.jstree.reference('treeContent');
        ref.save_state();

        location.assign(parent.basePath + '/tech/piece_yardage_onesize/auxiliary/2/' + $self.parent().parent().attr("_mash_id") + '/' + $("#NodeId").val() + '/edit.html');
    }
    DoDelete($self) {
        let _params = super.GetFilter(this.$pagination.attr("_msh_page"));
        // 设置条件
        _params = this.SetCriterion(_params);
        _params['HeaderId'] = $self.parent().parent().attr("_mash_id");
        _params['DeletedBy'] = $("#UserId").val();
        _params['DeletedStyleNo'] = $self.parent().parent().find("td").eq(3).text();
        super.DoDelete(_params, function (_this, data) {
            if (data.Success === true) {
                _this.BuildDataTable(data);
            } else {
                _this.EmptyTableContent();
            }
            ShowSuccessMessagePanel("删除成功。");
        });
    }
    // 设置行选择后的状态
    SetRowStatus($self) {
        super.AdjustRowStatus($self, ($row, index) => {
            let key = $self.val();
            let item = {};
            $('#tabData02 tbody tr:eq(' + index + ')').addClass("row__selected");
            // 设置 编辑、删除按钮失效
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", "");
            $row.children('td').eq(2).children('span').eq(0).attr("onclick", "");
            // 为翻页选择做准备
            item["headerId"] = key;
            this.selectedItemList[key] = item;
        }, ($row, index) => {
            let key = $self.val();
            $('#tabData02 tbody tr:eq(' + index + ')').removeClass("row__selected");
            // 设置 编辑、删除按钮有效
            let _event_edit_onclick = '_Instance.DoEdit($(this))';
            let _event_delete_onclick = '_Instance.DoDelete($(this))';
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", _event_edit_onclick);
            $row.children('td').eq(2).children('span').eq(0).attr("onclick", _event_delete_onclick);
            delete this.selectedItemList[key];
        });
    }
    // 每次翻页都恢复选定结果
    ResetSelectRowStatus() {
        let _this = this;
        $("#tabData01 tbody").find("tr").each(function (index) {
            let key = $(this).attr("_mash_id");
            if (_this.selectedItemList[key] !== undefined) {
                $(this).children("td").eq(0).children("label").eq(0).children("input[type='checkbox'][name='_check_row']").eq(0).prop('checked', true);
                $(this).addClass("row__selected");
                $('#tabData02 tbody tr:eq(' + index + ')').addClass("row__selected");
            }
        });
        // 设置选择全部的状态
        let n = $("input[type='checkbox'][name='_check_row']:checked").length;
        if (n < $("#tabData01 tbody").find("tr").length || n === 0) {
            $("#CheckAll").prop("checked", false);
        } else {
            $("#CheckAll").prop("checked", true);
        }
    }
    GetDragData() {
        let _this = this;
        this.draggedItemList = [];
        if ($("input[type='checkbox'][name='_check_row']:checked").length > 0) {
            $("input[type='checkbox'][name='_check_row']:checked").each(function () {
                let item = {};
                item['headerId'] = $(this).val();
                item['updatedBy'] = $("#UserId").val();
                _this.draggedItemList.push(item);
            });
        } else {
            let item = {};
            item['headerId'] = parseInt($("#tabData01 tbody tr.rowMoved").attr("_mash_id"));
            item['updatedBy'] = parseInt($("#UserId").val());
            _this.draggedItemList.push(item);
        }
    }
    SaveFilters() {
        let _filters = new Array();
        _filters.push($("#Begin").val());
        _filters.push($("#End").val());
        _filters.push($("#StyleNoFilterValue").val());
        _filters.push($("#CustomerNameFilterValue").val());
        _filters.push($("#DesignedByNameFilterValue").val());
        _filters.push($("#GradedByNameFilterValue").val());
        _filters.push($("#DescriptionFilterValue").val());
        $.cookie("piece_yardage_onesize_auxiliary_list_fiters", _filters.join(","));
    }
    RestoreFilters() {
        if ($.cookie("piece_yardage_onesize_auxiliary_list_fiters") !== undefined && this.flag !== 0) {
            let _filters = $.cookie("piece_yardage_onesize_auxiliary_list_fiters").split(',');
            $("#Begin").val(_filters[0]);
            $("#End").val(_filters[1]);
            $("#StyleNoFilterValue").val(_filters[2]);
            $("#CustomerNameFilterValue").val(_filters[3]);
            $("#DesignedByNameFilterValue").val(_filters[4]);
            $("#GradedByNameFilterValue").val(_filters[5]);
            $("#DescriptionFilterValue").val(_filters[6]);
        } else {
            $("#Begin").val("");
            $("#End").val("");
            $("#StyleNoFilterValue").val("");
            $("#CustomerNameFilterValue").val("");
            $("#DesignedByNameFilterValue").val("");
            $("#GradedByNameFilterValue").val("");
            $("#DescriptionFilterValue").val("");
        }
    }
    ScrollTo() {
        $('#divH2').scrollLeft($('#divD2').scrollLeft());
        $('#divD1').scrollTop($('#divD2').scrollTop());
    }
    Expand() {
        let _w = $(window).width();
        let wLeftList = 647; // 左边列表固定宽度
        $("#btnPanel_01").show();
        $("#treeArea").show();
        $("#panelSplitter").css({left: 250});
        $("#panelSplitter").children().removeClass("fa-angle-double-right").addClass("fa-angle-double-left");
        $("#panelSplitter").attr("title", "折叠目录");

        $("#btnPanel_02").css({left: 275});
        $("#grid__wrapper").css({left: 275, width: _w - 8 - 275});
        $("#divH2").css({left: 0, width: _w - 8 - 275 - wLeftList});
        $("#divD2").css({left: -1, width: _w - 8 - 274 - wLeftList});
    }
    Collapse() {
        let _w = $(window).width();
        let wLeftList = 647; //左边列表固定宽度
        $("#btnPanel_01").hide();
        $("#treeArea").hide();
        $("#panelSplitter").css({left: 0});
        $("#panelSplitter").children().removeClass("fa-angle-double-left").addClass("fa-angle-double-right");
        $("#panelSplitter").attr("title", "展开目录");

        $("#btnPanel_02").css({left: 24});
        $("#grid__wrapper").css({width: _w - 24 - 8, left: 24});
        $("#divH2").css({left: 0, width: _w - 8 - 24 - wLeftList});
        $("#divD2").css({left: -1, width: _w - 8 - 23 - wLeftList});
    }
}

class MyPageTree extends BaseTree {
    constructor(instance, getTreeUrl, dragUrl, stateKey) {
        super(instance, getTreeUrl, dragUrl, stateKey);
    }
}

var _Instance = null;
var _InstanceTree = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let flag = jQuery.url.param("flag") === undefined ? 0 : jQuery.url.param("flag");
    $("#page-size").val($.cookie("piece_yardage_onesize_auxiliary_list_pagesize") === undefined ? 15 : $.cookie("piece_yardage_onesize_auxiliary_list_pagesize"));
    // 删除已经保存的检索后的数据列表标识数组
    $.cookie("piece_yardage_onesize_auxiliary_list_result", null);

    _Instance = new MyPage(0, null, flag,
            $("#page-size"),
            $("abbr.page_indicator_block,#wrapper__navbar"),
            "piece_yardage_onesize_auxiliary_list_pagesize",
            "piece_yardage_onesize_auxiliary_list_pageindex",
            "piece_yardage_onesize_auxiliary_list_result",
            "/tech/piece_yardage_onesize/fetchForPage.html",
            "/tech/piece_yardage_onesize/delete.html");
    _InstanceTree = new MyPageTree(_Instance,
            "/tech/piece_yardage/catalogue/tree.html",
            "/tech/piece_yardage_onesize/changeCatalogue.html",
            "piece_yardage_onesize_list_selected_node");

    //设置分页控制 （操作区域）
    $("#wrapper__navbar").swPagination({
        link_string: '/?page={page_number}',
        max_page: null,
        paged: function (page) {
            $("abbr.page_indicator_block,#wrapper__navbar").attr("_msh_page", page);
            _Instance.FetchForPage(page);
        }
    });
    /*
     // 设置表格排序字段
     $("#tabHeader01").wxTableSorter({
     sortList: [[4, 0], [5, 2], [6, 2]], // 第一个表示列的序号，第二个表示排序种类
     headers: {4: {sorter: false}, 5: {sorter: false}, 6: {sorter: false}},
     columnList: [[1, "M.MaterialCode"], [2, "M.MaterialName"], [3, "CO.ShortName"]],
     detailList: $("#tabData01"),
     sort: function (orderBy) {
     _Instance.SortTable(orderBy);
     }
     });*/
    /*$("#tabHeader02").wxTableSorter({
     sortList: [[0, 2]], // 第一个表示列的序号，第二个表示排序种类
     headers: {0: {sorter: false}},
     columnList: [[1, "C0.CompanyName"]],
     detailList: $("#tabData02"),
     sort: function (orderBy) {
     _Instance.SortTable(orderBy);
     }
     });*/

    $("#panelSplitter").click(function () {
        if ($(this).children("i").hasClass("fa-angle-double-left")) {
            _Instance.Collapse();
        } else {
            _Instance.Expand();
        }
    });

    _Instance.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    let wLeftList = 647; // 左边列表固定宽度
    let h = $(window).height();
    let w = $(window).width();

    $("#treeArea").css({height: h - 110});
    if ($("#panelSplitter").children().hasClass("fa-angle-double-left") === true) {
        $("#divH2").css({left: 0, width: w - 8 - 275 - wLeftList});
        $("#divD2").css({left: -1, width: w - 8 - 274 - wLeftList});
    } else {
        $("#divH2").css({left: 0, width: w - 8 - 24 - wLeftList});
        $("#divD2").css({left: -1, width: w - 8 - 23 - wLeftList});
    }
}